package com.kxc.controller;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.kxc.entity.MoniItem;
import com.kxc.entity.MoniPoint;
import com.kxc.service.MoniItemService;
import com.kxc.service.MoniPointService;
import com.kxc.service.PublishSfService;

/**
 * 是否开启定时任务
 * 
 * @author jjq
 * @data 2023年3月13日
 * @version
 */
@Component
public class TimerController implements ApplicationRunner {

	@Autowired
	private PublishSfService publishTPLInfoService;
	
	@Autowired
	private MoniItemService itemService;
	
	@Autowired
	private MoniPointService moniPointService;
	
	
	 
	int sfFrequency=240;
	Timer timer = new Timer();
	TimerTask sfTask = null;
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public void run(ApplicationArguments arg0) throws Exception {
		
		// 1、定时发送库水位设备信息
		gnssrTimerTask();
		
	}

	/**
	 * 定时发送库水位设备信息
	 * @param frequency 
	 */
	public void gnssrTimerTask() {
		
		sfTask = new TimerTask() {
			@Override
			public void run() {
				try {
					MoniItem item = itemService.getByItemNum("SurfaceDisplacement");
					int sdf = item.getFreq();
					if(sdf!=sfFrequency){
						sfFrequency=sdf;
						sfTask.cancel();
						timer.purge();
						sfTask = null;
						gnssrTimerTask();
					}
					List<MoniPoint> points = moniPointService.findByMoniItem("SurfaceDisplacement");
					publishTPLInfoService.saveRealTimeDataInfo(points,sfFrequency);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		timer.scheduleAtFixedRate(sfTask, 1000, sfFrequency*60*1000);
	}
}